package org.devf.fork.imsimulator.view;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import org.devf.fork.imsimulator.http.ApiClientFactory;
import org.devf.fork.imsimulator.http.pojo.ChatImageDto;
import org.devf.fork.imsimulator.model.ChatMessageItem;
import org.devf.fork.imsimulator.model.UserModel;
import org.devf.fork.imsimulator.service.ChatService;
import org.devf.fork.imsimulator.service.ServiceFactory;
import org.devf.fork.imsimulator.service.TokenMgr;
import org.devf.fork.imsimulator.service.api.UserApiClient;
import org.devf.fork.imsimulator.service.vo.UserExtendModel;
import org.devf.fork.imsimulator.socket.dto.BasePackets;
import org.devf.fork.imsimulator.socket.dto.BizType;
import org.devf.fork.imsimulator.socket.dto.MsgContents;
import org.devf.fork.imsimulator.socket.handler.MsgHandlerFactory;
import org.devf.fork.imsimulator.socket.handler.listener.ChatListener;
import org.devf.fork.imsimulator.socket.handler.listener.FriendStateListener;
import org.devf.fork.imsimulator.socket.handler.listener.HeartListener;
import org.devf.fork.imsimulator.socket.packet.PacketsFactory;
import org.devf.fork.imsimulator.view.extend.ChatMessageListCel;
import org.devf.fork.imsimulator.view.extend.DragFileListener;
import org.devf.fork.imsimulator.view.extend.FriendListCel;
import org.devf.fork.imsimulator.view.layout.ChatItem;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static org.devf.fork.imsimulator.model.HttpConstant.WebUrl.CHAT_IMAGE_POST;

public class ChatController extends BaseController implements ChatListener, HeartListener, FriendStateListener, DragFileListener {
    @FXML
    public Label curFriendTitle;
    @FXML
    public Label heartLabel;
    @FXML
    public ListView<ChatItem> chatListView;
    @FXML
    private ListView<UserExtendModel> friendListView;
    @FXML
    private TextArea messageTextArea;

    private final ChatService chatService = ServiceFactory.getChatService();
    private UserExtendModel focusFriendUser;


    @FXML
    public void initialize() {
        friendListView.setCellFactory(param -> new FriendListCel());
        friendListView.setOnMouseClicked(event -> {
            UserExtendModel selectedItem = friendListView.getSelectionModel().getSelectedItem();
            if (selectedItem != null) {
                focusFriendUser = selectedItem;
                curFriendTitle.setText(focusFriendUser.getNikname() + "(" + focusFriendUser.getOnlineStatusStr() + ")");
            }
        });

        // 在这里可以初始化好友列表和其他界面元素
        List<UserExtendModel> friends = UserApiClient.getFriends();
        friendListView.getItems().addAll(friends);
        chatListView.setCellFactory(param -> new ChatMessageListCel());
        messageTextArea.setOnKeyReleased(event -> {
            if (event.getCode().equals(KeyCode.ENTER)) {
                sendMessage();
            }
        });

        chatService.addEventOfDragFile(chatListView.getParent(),this);

        //注册服务消息监听器
        MsgHandlerFactory.ChatHandler().register(this);
        MsgHandlerFactory.HeartHandler().register(this);
        MsgHandlerFactory.FriendOnlineHandler().register(this);
    }


    @FXML
    private void sendMessage() {
        if (!TokenMgr.isLogin()) {
            AlterHelp.alter("请重新登录");
        }
        if (null == focusFriendUser) {
            AlterHelp.alter("请选择好友进行聊天");
        }
        if (null == messageTextArea.getText()) {
            return;
        }

        BasePackets packets = PacketsFactory.getSingleChatPackets(messageTextArea.getText(), focusFriendUser.getFriendRelationId());
        addCellToChatListView(TokenMgr.userModel, packets);

        chatService.syncSendChatMsg(focusFriendUser, packets);

        // 清空输入框
        messageTextArea.clear();
    }

    private void addCellToChatListView(UserModel userModel, BasePackets packets) {
        ChatMessageItem chatMessageItem = new ChatMessageItem();
        BeanUtil.copyProperties(packets, chatMessageItem);
        chatMessageItem.setMsgStatus(packets.getMsgStatus());
        chatMessageItem.setMessage(JSONUtil.toBean(JSONUtil.toJsonStr(packets.getContents()), MsgContents.class));
        chatMessageItem.setFromUser(userModel);
        chatMessageItem.setDestUser(null);
        chatListView.getItems().add(new ChatItem(chatMessageItem));
    }

    private void updateCellToListView(BasePackets packets) {
        chatListView.getItems()
                .stream()
                .filter(c -> Objects.equals(c.getMessageItem().getPackageId(), packets.getPackageId()))
                .findFirst()
                .ifPresent(item -> {
                    item.getMessageItem()
                            .setMsgStatus(packets.getMsgStatus());
                });
    }

    @Override
    public void getMessage(BasePackets packets) {
        //获取到消息
        if (null == packets.getContents()) {
            return;
        }
        toShowCurChatListView(packets);
    }

    private void toShowCurChatListView(BasePackets packets) {
        refreshView(()->{
            if (packets.getAck()) {
                updateCellToListView(packets);
                return;
            }

            if (focusFriendUser == null) {
                return;
            }
            addCellToChatListView(focusFriendUser, packets);
        });
    }


    @Override
    public void heart(boolean result) {
        refreshView(() -> {
            heartLabel.setText("   当前心跳 (" + (result ? LocalDateTimeUtil.format(LocalDateTime.now(), "HH:mm:ss") : "异常") + ")");
        });
    }

    /**
     * 好友上线->更新好友列表
     *
     * @param friend 好友
     */
    @Override
    public void friendOnline(UserExtendModel friend) {
        for (UserExtendModel item : friendListView.getItems()) {
            if (Objects.equals(item.getId(), friend.getId())) {
                item.setOnlineStatus(friend.getOnlineStatus());
                friendListView.refresh();
            }
        }
    }

    @Override
    public void onDragImageOfSend(File file) {
        // 上传并发送图片，这里需要实现上传和发送逻辑
        ChatImageDto chatImageDto = new ChatImageDto();
        chatImageDto.setBizType(BizType.SINGLE_CHAT.name());
        chatImageDto.setDestId(focusFriendUser.getFriendRelationId());
        chatImageDto.setFile(file);
        String result = ApiClientFactory.getImageHttpClient().postImage(CHAT_IMAGE_POST,chatImageDto);
        System.out.println(result);


        // 上传完成后，可以在聊天室中显示图片
//                ImageView imageView = new ImageView();
//                imageView.setImage(new javafx.scene.image.Image(db.getFiles().get(0).toURI().toString()));
//                chatRoom.getChildren().add(imageView);
    }

//    public static void main(String[] args) {
//        TokenMgr.token = "2ce21c04ba584403ac90a4d7f7da07bd";
//        ChatImageDto chatImageDto = new ChatImageDto();
//        chatImageDto.setBizType(BizType.SINGLE_CHAT.name());
//        chatImageDto.setDestId(1L);
//        chatImageDto.setFile(new File("/Users/taofuxn/Desktop/WechatIMG11867.png"));
//        String result = ApiClientFactory.getImageHttpClient()
//                .postImage(CHAT_IMAGE_POST,chatImageDto);
//        System.out.println(result);
//    }
}